<script>

export default {
  name: 'ElectronicSignatures',
  data() {
    return {
      lineWidth: 6,
      lineColor: '#000000',
      bgColor: '',
      resultImg: '',
      isCrop: false,
      innerValue: this.value
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  watch: {
    value: function(innerValue) {
      this.innerValue = innerValue;
    }
  },
  methods: {
    handleReset() {
      this.$refs.esign.reset();
      this.resultImg = '';
      this.innerValue = null;
      this.$emit('change', this.innerValue);
    },
    //生成签名图片..
    handleGenerate() {
      this.$refs.esign.generate().then(res => {
        let randnum = Math.random() * 10000000000000
        randnum = Math.floor(randnum)
        let fileName = "esign/" + randnum + '.png'
        let file = this.dataURLtoFile(res, fileName);
        // /reportApproval/report/fileUplod
        const formData = new FormData();
        formData.append('file', file); // 将文件添加到 FormData 对象
        this.$http.post('/reportApproval/report/fileUplod', formData, {
          headers: {'Content-Type': 'multipart/form-data'}
        }).then(res => {
          this.innerValue = res.data;
          this.$emit('change', this.innerValue);
        })
      }).catch(err => {
        console.log(err);
        this.$message.error('请签名之后提交！')
      })
    },
    dataURLtoFile(dataurl, filename) {
      let arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, {type: mime});
    },
  }
}
</script>

<template>
<div>
  <vue-esign v-if="!innerValue || innerValue === ''" style="border: 1px solid #000" ref="esign" :isCrop="isCrop" :width="600" :height="300" :lineWidth="lineWidth"
             :lineColor="lineColor" :bgColor.sync="bgColor"></vue-esign>
  <img v-else :src="innerValue" :width="300" :height="150" alt="">
  <div class="contro-container">
    <el-button v-if="!innerValue || innerValue === ''" type="danger" @click="handleReset">清空画板</el-button>
    <el-button v-if="!innerValue || innerValue === ''" type="primary" @click="handleGenerate">生成图片</el-button>
    <el-button v-else type="primary" @click="innerValue = null;">重制签名</el-button>
  </div>
</div>
</template>

<style scoped>

</style>